from tortoise import fields
from tortoise.models import Model

class Department(Model):
    dept_id = fields.CharField(max_length=225, description="部门ID")
    dept_name = fields.CharField(max_length=100, description="部门名称")
    description = fields.TextField(null=True, description="部门描述")
    parent_id = fields.CharField(max_length=225, null=True, description="父级部门ID")
    ancestors = fields.CharField(max_length=255, null=True, description="部门路径")
    level = fields.IntField(default=1, description="部门层级")
    order_num = fields.IntField(default=0, description="部门排序")
    permissions = fields.ManyToManyField(
        "models.Permission", 
        related_name="departments", 
        through="department_permission", 
        description="部门拥有的权限"
    )
    created_at = fields.DatetimeField(auto_now_add=True, description="创建时间")
    updated_at = fields.DatetimeField(auto_now=True, description="更新时间")
    
    class Meta:
        table = "department"
        table_description = "部门表"
        ordering = ["order_num", "dept_id"]
        
    async def get_children(self):
        """获取子部门"""
        return await Department.filter(parent_id=self.dept_id).order_by("order_num", "dept_id")

    async def get_all_children_recursive(self):
        """递归获取所有子部门"""
        children = await self.get_children()
        result = list(children)
        for child in children:
            child_children = await child.get_all_children_recursive()
            result.extend(child_children)
        return result

    async def get_parent(self):
        """获取父部门"""
        if self.parent_id:
            return await Department.get_or_none(dept_id=self.parent_id)
        return None
        
    @classmethod
    async def get_tree(cls):
        """获取部门树结构"""
        # 获取所有根部门
        root_departments = await cls.filter(parent_id__isnull=True).order_by("order_num", "dept_id")
        result = []
        
        for dept in root_departments:
            dept_dict = {
                "id": dept.id,  # Add the id field
                "dept_id": dept.dept_id,
                "dept_name": dept.dept_name,
                "description": dept.description,
                "parent_id": dept.parent_id,
                "parent_name": None,  # Root departments have no parent
                "ancestors": dept.ancestors,
                "level": dept.level,
                "order_num": dept.order_num,
                "created_at": str(dept.created_at),
                "updated_at": str(dept.updated_at),
                "children": await cls._get_children_tree(dept)
            }
            result.append(dept_dict)
            
        return result
    
    @classmethod
    async def _get_children_tree(cls, department):
        """递归获取子部门树结构"""
        children = await department.get_children()
        result = []
        
        for child in children:
            child_dict = {
                "id": child.id,  # Add the id field
                "dept_id": child.dept_id,
                "dept_name": child.dept_name,
                "description": child.description,
                "parent_id": child.parent_id,
                "parent_name": department.dept_name,  # Add parent department name
                "ancestors": child.ancestors,
                "level": child.level,
                "order_num": child.order_num,
                "created_at": str(child.created_at),
                "updated_at": str(child.updated_at),
                "children": await cls._get_children_tree(child)
            }
            result.append(child_dict)
            
        return result

class Permission(Model):
    id = fields.IntField(pk=True, description="自增主键")
    name = fields.CharField(max_length=100, unique=True, description="权限名称")
    code = fields.CharField(max_length=100, unique=True, description="权限代码")
    description = fields.TextField(null=True, description="权限描述")
    created_at = fields.DatetimeField(auto_now_add=True, description="创建时间")
    updated_at = fields.DatetimeField(auto_now=True, description="更新时间")

    class Meta:
        table = "permission"
        table_description = "权限表"
        ordering = ["name"]

class Role(Model):
    id = fields.IntField(pk=True, description="自增主键")
    name = fields.CharField(max_length=32, unique=True, description="角色名称")
    code = fields.CharField(max_length=32, unique=True, description="角色代码")
    description = fields.TextField(null=True, description="角色描述")
    permissions = fields.ManyToManyField(
        "models.Permission", 
        related_name="roles", 
        through="role_permission", 
        description="角色拥有的权限"
    )
    created_at = fields.DatetimeField(auto_now_add=True, description="创建时间")
    updated_at = fields.DatetimeField(auto_now=True, description="更新时间")
    department = fields.ForeignKeyField("models.Department", related_name="roles", null=True, description="所属部门")

    class Meta:
        table = "role"
        table_description = "角色表"
        ordering = ["name"]

class User(Model):
    id = fields.IntField(pk=True, description="自增主键")
    username = fields.CharField(max_length=32, unique=True, description="用户名", index=True)
    hashed_password = fields.CharField(max_length=128, description="哈希密码")
    name = fields.CharField(null=True, max_length=32, description="姓名")
    gender = fields.CharField(null=True, max_length=32, description="性别")
    birthday = fields.DateField(null=True, description="生日")
    address = fields.CharField(null=True, max_length=128, description="地址")
    email = fields.CharField(null=True, max_length=128, description="邮箱")
    phone = fields.CharField(null=True, max_length=128, description="手机号")
    bio = fields.TextField(null=True, description="个人简介")
    avatar = fields.CharField(null=True, max_length=128, description="头像")
    status = fields.CharField(default="启用", max_length=32, description="状态")
    is_superuser = fields.BooleanField(default=False, description="是否超级用户")
    is_active = fields.BooleanField(default=True, description="是否激活")
    roles = fields.ManyToManyField(
        "models.Role", 
        related_name="users", 
        through="user_role", 
        description="用户拥有的角色"
    )
    department = fields.ForeignKeyField("models.Department", related_name="users", null=True, description="所属部门")
    created_at = fields.DatetimeField(auto_now_add=True, description="创建时间")
    updated_at = fields.DatetimeField(auto_now=True, description="更新时间")

    class Meta:
        table = "user"
        table_description = "用户表"
        ordering = ["-created_at"] 